<?php

namespace app\company\service\user_profile\userArchive\selfTesting;

use app\admin\service\user_profile\userArchive\evaluationArchive\EvaluationArchiveService;
use app\admin\service\UserService;
use app\common\Message;
use app\model\archives_model\UserArchiveModel;
use app\model\UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Service;

class SelfTestingService extends Service
{
    use Message;

    /**
     * @param $data
     * @return true
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function getOverview($data): bool
    {
        //用户基本信息
        $getUserInfo = new EvaluationArchiveService($this->app);
        $info = $getUserInfo->getUserInfo($data);
        //个人自评档案统计
        if(check_array_key('isAbandon',$data)){
            //废弃档案数据
            $wheres = [
                ['user_id','=',$data['user_id']],
                ['is_repeal','=',1],
                ['type_id','=',1],
            ];
        }else{
            //正常档案数据
            $wheres = [
                ['user_id','=',$data['user_id']],
                ['is_repeal','=',0],
                ['type_id','=',1],
            ];
        }
        $field = ['id,user_id,time,source'];
        $recode = UserArchiveModel::query()->where($wheres)->field($field)->select();
        $totalCount = count($recode);
        if($totalCount>0){
            $ret = [
                'max_time' => 0,//最新一次的时间
                'min_time' => 0,//档案首次建立时间
                'to_date' => 0,//距今天数
                'total' => $totalCount,//总数
                'total_proportion' => 100,
                'self' => 0,
                'self_proportion' => 0,
                'online' => 0,
                'online_proportion' => 0,
                'offline' => 0,
                'offline_proportion' => 0,
                'team' => 0,
                'team_proportion' => 0,
            ];
            if ($ret['total'] > 0) {
                $timeArray = array_column($recode->toArray(), 'time');
                $ret['min_time'] = min($timeArray);
                $ret['max_time'] = max($timeArray);
                $ret['to_date'] = ceil((time() - $ret['min_time']) / (24 * 60 * 60));
                // 初始化来源统计数组
                $sourceCount = array_fill_keys([1, 2, 5, 6, 7], 0);
                // 统计每种来源的数量
                foreach ($recode as $item) {
                    if (isset($sourceCount[$item['source']])) {
                        $sourceCount[$item['source']]++;
                    }
                }
                // 映射渠道到返回结果结构
                $channelMapping = [
                    1 => 'self',
                    2 => 'online',
                    3 => 'offline',
                    4 => 'team',
                ];
                // 更新返回结果
                foreach ($sourceCount as $channel => $count) {
                    if (isset($channelMapping[$channel])) {
                        $ret[$channelMapping[$channel]] = $count;
                        $proportionKey = $channelMapping[$channel] . '_proportion';
                        $ret[$proportionKey] = $totalCount > 0 ? removeTrailingZero(number_format($count / $totalCount * 100, 1)) : 0;
                    }
                }
            }
            $info['archives'] = $ret;
        }else{
            $info = [];
        }
        $this->result = $info;
        $this->message = '操作成功！';
        return true;
    }


    /**
     * @param $data
     * @return bool
     * @throws DbException
     */
    public function getRecode($data): bool
    {
        if(check_array_key('isAbandon',$data)){
            //废弃档案数据
            $where = [
                ['user_id', '=', $data['user_id']],
                ['type_id', '=', 1],
                ['is_repeal', '=', 1],
            ];
        }else{
            //正常档案数据
            $where = [
                ['user_id', '=', $data['user_id']],
                ['type_id', '=', 1],
                ['is_repeal', '=', 0],
            ];
        }
        $return = UserArchiveModel::query()->where($where)->with(['getUserInfo'])->field('id,update_uid,type_id,time,source')
            ->order('time desc')->paginate($data['pageSize']);
        $ret =$return->toArray();
        # 计算当前页的起始索引
        $start_index = ($ret['current_page'] - 1) * $ret['per_page'];
        // 更新数据并添加 num 字段
        foreach($return as $index => &$item){
            $item['num'] = ($start_index + $index === $ret['total'] - 1) ? 1 : ($ret['total'] - ($start_index + $index));
            $prefix = '个人自评表';
            $prefixNext = ',用户填写后更新。';
            /* 来源说明 - 开始 */
            $sources = [
                1 => [
                    'source' => '个人信息设置',
                    'describe' => '用户自行更新' . $prefix . '。'
                ],
                2 => [
                    'source' => '线下预约',
                    'describe' => '线下预约时,由咨询师发布' . $prefix . $prefixNext
                ],
                3 => [
                    'source' => '线上咨询',
                    'describe' => '线上咨询时,由咨询师发布' . $prefix . $prefixNext
                ],
                4 => [
                    'source' => '团体活动自评',
                    'describe' => '团体活动时,由管理员发布' . $prefix . $prefixNext
                ]
            ];
            // 确保 $item['source'] 存在并且是有效值
            $sourceKey = $item['source'] ?? null;
            if ($sourceKey !== null && isset($sources[$sourceKey])) {
                $item['source'] = $sources[$sourceKey]['source'];
                $item['describe'] = $sources[$sourceKey]['describe'];
            } else {
                // 设置默认值（可选）
                $item['source'] = '未知来源';
                $item['describe'] = '无可用描述。';
            }
            /* 来源说明 - 结束 */
        }
        $this->result = $return;
        $this->message = '操作成功！';
        return true;
    }
}